<?php

namespace App\Http\Middleware;

use App\Trip\Crypt\AppKey;
use Carbon\Carbon;
use Closure;
use Exception;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class VerifyHeader
{
    use \App\Trip\Traits\Response;

    /**
     * Handle an incoming request.
     *
     * @param Request                                       $request
     * @param Closure(Request): (Response|RedirectResponse) $next
     *
     * @return Response|RedirectResponse
     * @throws Exception
     */
    public function handle(Request $request, Closure $next)
    {
        // 1 解析appid
        $app_key = $request->header('App-Key') ?: $request->header('app-key');
        $app_id  = $app_key ? AppKey::decrypt($app_key) : '';
        if (!$app_id || !AppKey::isAppValid($app_id)) {
            return $this->error(502, '未识别的数据', [], 502);
        }
        // 2 通过time-sign 过滤过期的请求

        $time_sign = $request->header('Time-Sign', '') ?: $request->header('time-sign', '');
        $time      = $time_sign ? AppKey::decrypt($time_sign) : 0;
        if ($time < Carbon::now()->timestamp - 10) {
//            return response([], 502);
        }

        // 3 language
        $language = $request->header('language');
        $cl       = app()->getLocale();
        if ($language && $language != $cl) {
            app()->setLocale($language);
        }
        // 处理火车站版本
        $station_version = $request->header('Station-Version');
        $response        = $next($request);
        if ($station_version && $station_version != official_station_version()) {
            // 站点需要更新
            $response->headers->set('Station-Update', true);
        }
        return $response;
    }
}
